﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using BitMiracle.Docotic.Pdf;
using System.Xml;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Core;
using BussinesLogic;
using System.Drawing.Design;


namespace FoliaturaDigital
{
    
    public partial class Frm_Documentos : Form
    {
        private Foliatura.Controller controlador;
        public Frm_Documentos()
        {
            controlador = Foliatura.Controller.Instance();
            InitializeComponent();
        }

        public string path; 
        public object Target; 
        public object SourceFile;
        bool isEdit = false;
        bool isNuevo = true;
        string Tick;
        
        private void Frm_Documentos_Load(object sender, EventArgs e)
        {
            fillData();
            //DataBind();
            BindDataGrid();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;
            path = Functions.getpath();
            Tick = now.Ticks.ToString();
            Target = path + "\\" + Tick + ".pdf";
            SourceFile = Functions.selectFile();
            this.txtDocumento.Text = SourceFile.ToString();
            
            
        }

        public void BindDataGrid()
        {
            controlador.documentos = BussinesLogic.Documento.getDocuments(controlador.expediente.NoExpediente);
            ArrayList arr = controlador.documentos;
            dgDocumentos.DataSource = arr;
            if(arr != null && arr.Count>0) 
                   this.SetupDataGridView();
        }
        public void DataBind()
        {
            if (controlador.documento != null)
            {
                this.controlador.documento.NoExpediente = controlador.expediente.NoExpediente;
                this.controlador.documento.FechaRecepcion = this.dtpRecepcion.Value;
                this.controlador.documento.FechaDocumento = dtpDocumento.Value; ;
                this.controlador.documento.CodDocumento = Tick; //Path.GetFileName(this.txtDocumento.Text);
                this.controlador.documento.documento = Path.GetFileName(this.txtDocumento.Text);
                this.controlador.documento.Descripcion = this.txtDescripcion.Text;
                this.controlador.documento.NumPaginas = Int32.Parse(this.lblPag.Text);    
                this.controlador.documento.Tipo = "WORD";
                this.controlador.documento.Usuario = this.controlador.user.Username;
                this.controlador.documento.documento = Path.GetFileName(this.txtDocumento.Text);
 
                
            }
            this.lblExpediente.Text = this.controlador.expediente.NoExpediente;
            //SetupLayout();
            //if (dgExpedientes.Rows.Count > 0) SetupDataGridView();
        }

        private void fillData()
        {

            if (controlador.documento == null)
            {
                controlador.documento = new Documento();
                controlador.documento.FechaDocumento = DateTime.Now.Date;
                controlador.documento.FechaRecepcion = DateTime.Now.Date;
            }
            this.lblUser.Text = controlador.user.Nombre1 + " " + controlador.user.Apellido1;
            this.lblExpediente.Text = controlador.expediente.NoExpediente;
            this.lblPag.Text = controlador.documento.NumPaginas.ToString();
            this.txtDescripcion.Text = controlador.documento.Descripcion;
            this.txtDocumento.Text = this.controlador.documento.documento;
            this.lblDocumento.Text = this.controlador.documento.CodDocumento;
            this.dtpDocumento.Value = this.controlador.documento.FechaDocumento;
            this.dtpRecepcion.Value = this.controlador.documento.FechaRecepcion;
        }

        private void SetupDataGridView()
        {
            //this.Controls.Add(dgDocumentos);
            //dgDocumentos.Name = "dgDocumentos";
            dgDocumentos.Location = new Point(8, 8);
            dgDocumentos.Size = new Size(500, 250);
            dgDocumentos.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
            dgDocumentos.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
            dgDocumentos.CellBorderStyle = DataGridViewCellBorderStyle.Single;
            dgDocumentos.GridColor = System.Drawing.Color.Black;
            dgDocumentos.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgDocumentos.EditMode = DataGridViewEditMode.EditProgrammatically;
            dgDocumentos.RowHeadersVisible = false;

            dgDocumentos.Columns[0].Visible = false;
            dgDocumentos.Columns[1].Visible = true;
            dgDocumentos.Columns[1].Width = 150;
            dgDocumentos.Columns[2].Visible = true;
            dgDocumentos.Columns[3].Visible = false;
            dgDocumentos.Columns[4].Visible = true;
            dgDocumentos.Columns[4].Width = 400;
            dgDocumentos.Columns[5].Visible = false;
            dgDocumentos.Columns[6].Visible = false;
            dgDocumentos.Columns[7].Visible = false;
            dgDocumentos.Columns[8].Visible = false;
            dgDocumentos.Columns[9].Visible = false;
            
            dgDocumentos.Columns[4].DefaultCellStyle.Font = new System.Drawing.Font(dgDocumentos.DefaultCellStyle.Font, FontStyle.Italic);

            dgDocumentos.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgDocumentos.MultiSelect = false;
            dgDocumentos.Dock = DockStyle.Fill;

            dgDocumentos.BackgroundColor = System.Drawing.Color.LightGray;
            dgDocumentos.BorderStyle = BorderStyle.Fixed3D;
            dgDocumentos.AllowUserToOrderColumns = true;
            dgDocumentos.DefaultCellStyle.SelectionForeColor = System.Drawing.Color.White;
            dgDocumentos.DefaultCellStyle.SelectionBackColor = System.Drawing.Color.Black;
            dgDocumentos.DefaultCellStyle.ForeColor = System.Drawing.Color.Black;
            dgDocumentos.DefaultCellStyle.BackColor = System.Drawing.Color.White;
            //dgDocumentos.RowHeadersDefaultCellStyle.BackColor = System.Drawing.Color.WhiteSmoke;
            //dgDocumentos.RowHeadersDefaultCellStyle.ForeColor = System.Drawing.Color.Black;
            //dgDocumentos.ColumnHeadersDefaultCellStyle.SelectionBackColor = System.Drawing.Color.Blue;
            //dgDocumentos.ColumnHeadersDefaultCellStyle.SelectionForeColor = System.Drawing.Color.White;
            dgDocumentos.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font(dgDocumentos.Font, FontStyle.Bold);

            //dgDocumentos.CellFormatting += new DataGridViewCellFormattingEventHandler(dgExpedientes_CellFormatting);
             
        }

        private void btnGuardar_Click(object sender, EventArgs e)
        {
            string strxml = "";
            if (!adjuntarDocumento()) return;
            if (SourceFile == null || SourceFile.ToString() == "")
            {
                MessageBox.Show("No se ha seleccionado un archivo");
                //MessageBox.Show("El Archivo Seleccionado no es valido");
                return;
            }
            if (this.isNuevo)
            {
                DataBind();
                try
                {
                    this.controlador.documento.Create();
                    fillData();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
            else
            {
                DataBind();
                try
                {
                    this.controlador.portada.Update();
                    fillData();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
            BindDataGrid();
            try
            {
                strxml = Functions.SplitPdfByPages(Target.ToString(), 1, path, Tick, this.controlador.documento.id, controlador.expediente.NoExpediente, controlador.documento.CodDocumento, "DOC");
                this.controlador.documento.Adjuntar(strxml);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        private bool adjuntarDocumento()
        {
            DateTime now = DateTime.Now;

            if (SourceFile != null && SourceFile.ToString() != "")
            {
                object nullobj = System.Reflection.Missing.Value;

                Word.ApplicationClass ap = new Word.ApplicationClass();

                object FileFormat = Word.WdSaveFormat.wdFormatDocument; ;
                object SaveFileFormat = Word.WdSaveFormat.wdFormatPDF;
                object pageBreak = Word.WdBreakType.wdPageBreak;
                object SaveChanges = false;
                object OriginalFormat = false;
                object SaveFormsData = true;
                object InsertLineBreaks = true;
                object LineEnding = Microsoft.Office.Interop.Word.WdLineEndingType.wdCRLF;

                try
                {
                    Word.Document doc = ap.Documents.Open(ref SourceFile, ref nullobj, ref nullobj,
                                              ref nullobj, ref nullobj, ref nullobj,
                                              ref nullobj, ref nullobj, ref nullobj,
                                              ref FileFormat, ref nullobj, ref nullobj,
                                              ref nullobj, ref nullobj, ref nullobj, ref nullobj);

                    if (doc.Signatures.Count == 0)
                    {
                        doc.Close(ref SaveChanges, ref OriginalFormat, ref nullobj);
                        MessageBox.Show("El archivo seleccionado no contiene firma digital");
                        return false;
                    }

                    doc.SaveAs(ref Target, ref SaveFileFormat, ref nullobj,
                            ref nullobj, ref nullobj, ref nullobj,
                            ref nullobj, ref nullobj,
                            ref nullobj, ref nullobj,
                            ref nullobj, ref nullobj, ref InsertLineBreaks,
                            ref nullobj, ref LineEnding, ref nullobj);

                    doc.Close(ref SaveChanges, ref OriginalFormat, ref nullobj);

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Exception: " + ex.Message);
                    return false;
                }
            }
            return true;
        }

        private void btnCerrar_Click(object sender, EventArgs e)
        {
            controlador.documento = new Documento();
            this.Close();
        }

        private void label7_Click(object sender, EventArgs e)
        {

        }

        private void lblPag_Click(object sender, EventArgs e)
        {

        }

        private void dgDocumentos_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgDocumentos.Rows.Count > 0)
            {
                controlador.documento = ((BussinesLogic.Documento)this.dgDocumentos.Rows[e.RowIndex].DataBoundItem);
                fillData();
            }
        }      
        
    }
}